﻿<template>
    <div class="grWorkCard">
        <vxe-grid id="xGrid"
                  class="xGrid"
                  ref="xGrid"
                  :loading="loading"
                  border
                  resizable
                  show-overflow
                  keep-source
                  highlight-hover-row
                  :row-class-name="rowClassName"
                  :row-config="{ useKey: true }"
                  height="260"
                  align="center"
                  :print-config="{}"
                  :import-config="{}"
                  :export-config="{}"
                  :custom-config="{storage: true}"
                  :toolbar-config="tableToolbar"
                  :scroll-y="{ enabled: false }"
                  :columns="tableColumn"
                  :edit-config="editConfig"
                  :edit-rules="formRules"
                  :checkbox-config="{labelField: '', highlight: true, range: true}"
                  :seq-config="seqConfig"
                  :menu-config="menuConfig"
                  :data="tableData"
                  @page-change="handlePageChange"
                  @edit-actived="editActived"
                  @edit-closed="editClosed"
                  @checkbox-range-change="checkboxChange"
                  @checkbox-change="checkboxChange"
                  @checkbox-all="checkboxAll"
                  @menu-click="menuClick"
                  @cell-dblclick="handleCellDbClick">
            <template v-slot:toolbar_buttons>
                <div class="tableToolbar">
                    <div style="min-width: 70px; margin-block: auto; font-weight: 700; font-size: 16px; font-family: 'Noto Sans SC'; color: #303133;">工艺参数</div>
                    <!--<el-input v-model="searchName" size="mini" placeholder="输入名称查询" clearable class="tableToolbarTextL" style="width: 180px;" @change="getData(0)" />
    <el-button type="primary" size="mini" class="tableToolbarTextL" @click="getData(0)">查询</el-button>-->
                    <el-button style="margin-left:10px" type="primary" size="mini" v-if="subTaskInfo.sTaskID" @click="createAdd()">新增</el-button>
                    <el-button type="danger" size="mini" class="tableToolbarTextL" :disabled="selectedItems.length === 0" v-if="subTaskInfo.sTaskID" @click="deleteDeList()">批量删除</el-button>
                </div>
            </template>

            <template #operate="{ row }">
                <!--<el-link type="primary" class="elLinkBTN" @click="edit(row)">编辑</el-link>
    <el-link type="danger" class="elLinkBTN" @click="deleteDeData(row)">删除</el-link>-->
            </template>
            <!--<template v-slot:reverse>
                <div class="vxePageLeft">
                    <el-link type="primary" :underline="false" class="elLinkBTN" @click="fx">反选</el-link>
                </div>
            </template>
            <template v-slot:current_pageNum>
                <span class="vxe-pager--total">当前页 {{ tableData.length }} 条</span>
            </template>-->
        </vxe-grid>
        <vxe-modal v-model="tableShow" :loading="formLoading" :title="formTitle" width="900" :show-close="false" resize destroy-on-close>
            <template #default>
                <vxe-form ref="myform" :data="formInfo" :items="formItems" title-width="140" title-align="center" :rules="formRules">
                    <template #tempDistribution="{ data }">
                        <vxe-select v-model="formInfo.tempDistribution" placeholder="请选择" size="mini" transfer="true" clearable="true" @change="changeTempDistribution">
                            <vxe-option v-for="item of template.bedType" :key="item.value" :value="item.value" :label="item.label" />
                        </vxe-select>
                    </template>
                    <template #bedid="{ data }">
                        <vxe-select v-model="formInfo.bedid" placeholder="类型" size="mini" transfer="true" clearable="true" :multiple="false">
                            <vxe-option v-for="item of bedOption" :key="item.value" :value="item.value" :label="item.label" />
                        </vxe-select>
                    </template>
                    <template #laserPower="{ data }">
                        <vxe-input v-model="formInfo.laserPower" size="small" placeholder="请输入" @change="setLaserPower" clearable @clear="clearable" />
                    </template>
                    <template #pulseFrequency="{ data }">
                        <vxe-input v-model="formInfo.pulseFrequency" size="small" placeholder="请输入" @change="setPulseFrequency" clearable @clear="clearable" />
                    </template>
                </vxe-form>
                <div style="text-align:right">
                    <el-button @click="dialogFormClose">取 消</el-button>
                    <el-button type="primary" @click="dialogFormSave">确 定</el-button>
                </div>
            </template>
        </vxe-modal>
    </div>
</template>
<script>
    import prjAPI from '../../../request/Project/PrjAPI.js';
    import template from '../../../common/json/template.js';
    export default {
        props: {
            canEdit: { type: String, default: true },
            taskInfo: { type: Object, default: null },
            subTaskInfo: { type: Object, default: null },
            bedOption: { type: Array, default: [] },
            tableH: { type: Number, default: 0 },
        },
        data() {
            return {
                template,
                nowSelectTaskID: null,
                loading: false,
                formLoading: false,
                formTitle:'新增',
                searchName: '',
                formInfo: {},
                tableShow: false,
                bedOptionList:[],
                tableColumn: [
                    { field: 'checkbox', type: 'checkbox', title: '', fixed: 'left', width: 40 },
                    //{ field: 'drag', title: '排序', width: 100, fixed: 'left', visible: false, titlePrefix: { content: '拖动排序' }, slots: { default: 'dragBtn' } },
                    { type: 'seq', title: '序号', width: 70, fixed: 'left' },
                    { field: 'tempDistribution', title: '时序分布', minWidth: 80, formatter: ({ row }) => { return this.format(template.bedType, row.tempDistribution) } },
                    { field: 'bedName', title: '能量分布', minWidth: 100 },
                    { field: 'laserPower', title: '激光功率(W)', minWidth: 110, editRender: {}, },
                    { field: 'pulseFrequency', title: '脉冲频率(kHz)', minWidth: 120, editRender: {}, },
                    { field: 'pulsePower', title: '单脉冲能量(mJ)', minWidth: 125, editRender: {}, },
                    { field: 'pulseWidth', title: '脉宽(ns)', minWidth: 80, editRender: {}, },
                    { field: 'scanSpeed', title: '扫描速率(mm/s)', minWidth: 145, editRender: {}, },
                    { field: 'spotDiameter', title: '光斑直径(μm)', minWidth: 120, editRender: {}, },
                    { field: 'focalLength', title: '焦距(mm)', minWidth: 100, editRender: {}, },
                    { field: 'defocusAmount', title: '离焦量（mm）', minWidth: 120, editRender: {}, },
                    { field: 'washTimes', title: '清洗次数（N）', minWidth: 120, editRender: {}, },
                    { field: 'createTime', title: '创建时间', width: 100, formatter: ({ row }) => { return this.toDate(row.createTime) } },
                    { field: 'createUID', title: '创建人', width: 80, formatter: ({ row }) => { return this.getUser(row.createUID) } },
                    { field: 'remark', title: '备注', minWidth: 160, editRender: {}, },
                    //{ title: "操作", fixed: "right", width: 100, slots: { default: "operate" } },
                ],
                editConfig: {
                    enabled: false,
                    trigger: 'click',
                    mode: 'row',
                    showStatus: true
                },
                tableToolbar: {
                    refresh: {
                        query: () => this.getData()
                    },
                    import: false,
                    export: false,
                    print: false,
                    custom: false,
                    slots: {
                        buttons: 'toolbar_buttons'
                    }
                },
                tablePage: {
                    enabled: true,
                    total: 0,
                    currentPage: 1,
                    pageSize: 50,
                    align: 'right',
                    pageSizes: [50, 80],
                    layouts: [],
                    perfect: true,
                    slots: {
                       
                    }
                },
                seqConfig: {
                    seqMethod({ rowIndex }) {
                        return `光路${rowIndex + 1}`
                    }
                },
                menuConfig: {
                    enabled: false,
                    body: {
                        disabled: false,
                        trigger: 'default',
                        options: [
                            [
                                { name: '在上方插入行', code: 'above', prefixIcon: 'el-icon-arrow-up' },
                                { name: '在下方插入行', code: 'below', prefixIcon: 'el-icon-arrow-down' },
                            ],
                            [
                                { name: '应用于其他', code: 'use', prefixIcon: 'iconfont icon-fuzhi' },
                                { name: '应用于本页全部', code: 'useAll', prefixIcon: 'iconfont icon-niantie-1' },
                            ],
                            [
                                { name: '置顶', code: 'setTop', prefixIcon: 'iconfont icon-zhiding' },
                                { name: '移动', code: 'move', prefixIcon: 'el-icon-rank' },
                                { name: '删除', code: 'delete', prefixIcon: 'el-icon-delete' },
                            ]
                        ]
                    }
                },
                tableData: [],
                editActive: {
                    PGCS: false,
                    KYYJ: false
                },

                repairMeasure: [],
               
                formItems: [
                    { field: 'tempDistribution', title: '时序分布', span: 12, slots: { default: 'tempDistribution' } },
                    { field: 'bedid', title: '能量分布', span: 12, slots: { default: 'bedid' } },
                    { field: 'laserPower', title: '激光功率(W)', span: 12, slots: { default: 'laserPower' } },
                    { field: 'pulseFrequency', title: '脉冲频率(kHz)', span: 12, slots: { default: 'pulseFrequency' } },
                    { field: 'pulsePower', title: '单脉冲能量(mJ)', span: 12, itemRender: { name: '$input', props: { disabled: true } } },
                    { field: 'pulseWidth', title: '脉宽(ns)', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入' } } },
                    { field: 'scanSpeed', title: '扫描速率(mm/s)', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入' } } },
                    { field: 'spotDiameter', title: '光斑直径(μm)', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入' } } },
                    { field: 'focalLength', title: '焦距(mm)', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入' } } },
                    { field: 'defocusAmount', title: '离焦量（mm）', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入' } } },
                    { field: 'washTimes', title: '清洗次数（N）', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入' } } },
                    { field: 'remark', title: '备注', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入' } } },
                ],
                formRules: {
                    bedid: [{ required: true, message: '请选择能量分布' }],
                    laserPower: [{ required: true, message: '请填写激光功率' }],
                    pulseFrequency: [{ required: false, message: '请填写脉冲频率' }],
                    pulsePower: [{ required: false, message: '请填写脉冲频率' }],
                    pulseWidth: [{ required: false, message: '请填写脉宽' }],
                    scanSpeed: [{ required: true, message: '请填写扫描速率' }],
                    spotDiameter: [{ required: true, message: '请填写光斑直径' }],
                    focalLength: [{ required: true, message: '请填写焦距' }],
                    defocusAmount: [{ required: true, message: '请填写离焦量' }],
                    washTimes: [{ required: true, message: '请填写清洗次数' }],
                },

                showRelay: false,
                loadingRelay: false,
                nowSelectItem: null,
                loadingProf: true,
                prof: [],

                loadingWC: true,
                workCards: [],

                selectedItems: [],
                editItemNum: 0,

                tableModeMessage: null,
                nowSelectedRow: null,
                nowSelectedField: '',
                mode: '',
                modeOps: {
                    move: '移动',
                    use: '应用'
                },
                canUseField: {
                    isImportant: true,
                    itemName: true,
                    measure: true,
                    investigaion: true,
                    isInvestigate: true
                },

                showDragBtn: false,
                dragDataForm: null,

                otherFaultShow: false,
                faultFilter: null,
                placeholder2: '请输入故障项目名称查询',
                faultLoading: false,
                faultTable: [
                    { field: 'checkbox', type: 'checkbox', title: '', width: 40, fixed: 'left' },
                    { type: 'seq', title: '序号', width: 60, fixed: 'left' },
                    { field: 'itemName', minWidth: 360, title: '故障项目' },
                    { field: 'wcid', minWidth: 180, title: '所在工卡', formatter: ({ row }) => { return this.wcidArr[row.wcid] } },
                    { field: "profID", width: 200, title: "专业", formatter: ({ row }) => { return this.format(this.prof, row.profID) } },
                ],
                tableToolbar2: {
                    refresh: {
                        query: () => this.getOtherFault()
                    },
                    import: false,
                    export: false,
                    print: false,
                    custom: true,
                    slots: {
                        buttons: 'toolbar_buttons'
                    }
                },
                faultTablePage: {
                    total: 0,
                    currentPage: 1,
                    pageSize: 50,
                    align: 'right',
                    pageSizes: [50, 80],
                    layouts: ['Sizes', 'PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'FullJump', 'Total'],
                    perfect: true
                },
                faultTableExport: {
                    remote: true,
                    type: 'xlsx',
                    types: ['xlsx'],
                    modes: ['all'],
                    exportMethod: this.exportMethod
                },
                faultList: [],
                wcidArr: [],
                profType: '',
                selectedProjs: [],
                isFaultImportant: null,
                toolTipClose: '可点击[esc]按钮快速关闭当前弹窗',
            };
        },
        watch: {
            subTaskInfo(data) {
                if (data) {
                    this.getData();
                }
            },
            canEdit(data) {
            }
        },
        created() {
            this.watchKeyDown();
        },
        mounted() {
            
            //this.setTableColumn();
            //this.initRowDrop();
            //this.getData();
            if (this.workCardInfo) {
                //this.getData(0);
                //this.getAllRepairMeasure();
            }
        },
        beforeDestroy() {
        },
        methods: {
            visibilityChange() {
               
            },
            selectstartFunc() {
                var e = e || window.event;
                e.preventDefault();
            },
            getData(type) {
                if (!this.subTaskInfo.sTaskID) {
                    this.tableData = [];
                    return false
                };
                this.tableData = [];
                this.selectedItems = [];
                this.loading = true;
                var whereStr = "isDelete = 0 ";

                //if (!!this.searchName) {
                //    whereStr += " and prjName like '%" + this.searchName.trim() + "%' ";
                //}
                var params = {
                    staskID: this.subTaskInfo.sTaskID
                };
                prjAPI.getLaserList(params).then(res => {
                    this.tableData = res.map(x => {
                        x.bedName = this.bedOption.find(y => y.value === x.bedid).label;
                        return x
                    });
                    this.loading = false;
                    
                }).catch(err => {
                    this.loading = false;
                });
            },
            createAdd() {
                this.formInfo = {
                    prjID: this.taskInfo.prjID,
                    taskID: this.taskInfo.taskID,
                    sTaskID: this.subTaskInfo.sTaskID,
                    defocusAmount: null,
                    washTimes: null,
                    laserPower: null,
                    pulseFrequency: null,
                    pulsePower: null,
                    pulseWidth: null,
                    scanSpeed: null,
                    spotDiameter: null,
                    focalLength: null,
                    remark: '',
                    isDelete: false,
                    tempDistribution: 0,
                    bedid:'',
                };
                if (this.formInfo.tempDistribution === 0) {
                    this.formItems[4].itemRender.props.disabled = false;
                    this.formRules.pulseFrequency[0].required = false;
                    this.formRules.pulsePower[0].required = false;
                    this.formRules.pulseWidth[0].required = false;
                } else {
                    this.formItems[4].itemRender.props.disabled = true;
                    this.formRules.pulseFrequency[0].required = true;
                    this.formRules.pulsePower[0].required = true;
                    this.formRules.pulseWidth[0].required = true;
                };
                this.tableShow = true;
                this.formTitle = '新增工艺参数';

            },
            handleCellDbClick({ row }) {
                this.edit(row)
            },
            edit(row) {
                this.tableShow = true;
                this.formTitle = '编辑工艺参数';
                this.formInfo = row;
                if (row.tempDistribution === 0) {
                    this.formItems[4].itemRender.props.disabled = false;
                    this.formRules.pulseFrequency[0].required = false;
                    this.formRules.pulsePower[0].required = false;
                    this.formRules.pulseWidth[0].required = false;
                } else {
                    this.formItems[4].itemRender.props.disabled = true;
                    this.formRules.pulseFrequency[0].required = true;
                    this.formRules.pulsePower[0].required = true;
                    this.formRules.pulseWidth[0].required = true;
                };
            },
            deleteDeData(row) {
                this.$confirm(`是否删除该条数据?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.loading = true;
                    prjAPI.deleteLaser(row.laserDID).then(res => {
                        if (!res) {
                            this.$message({ type: 'warning', message: '删除失败!' });
                        }
                        this.$message({ type: 'success', message: '删除成功!' });
                        this.loading = false;
                        this.getData(0);
                    });
                }).catch(() => {
                    this.loading = false;
                });
            },
            deleteDeList() {
                var title = `是否删除已选中的 ${this.selectedItems.length} 条数据`;
                this.$confirm(title, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var data = this.selectedItems.map(e => e.laserDID);
                    this.loading = true;
                    prjAPI.deleteLaserList(data).then(res => {
                        if (!res) {
                            this.$message({ type: 'warning', message: '删除失败!' });
                        }
                        this.$message({ type: 'success', message: '删除成功!' });
                        this.loading = false;
                        this.getData(0);
                    }).catch(err => {
                        
                    });
                }).catch(() => { });
            },
            dialogFormClose() {
                this.tableShow = false;
                this.formInfo = {};
            },
            changeTempDistribution() {
                if (this.formInfo.tempDistribution === 0) {
                    this.formItems[4].itemRender.props.disabled = false;
                    this.formRules.pulseFrequency[0].required = false;
                    this.formRules.pulsePower[0].required = false;
                    this.formRules.pulseWidth[0].required = false;
                } else {
                    this.formItems[4].itemRender.props.disabled = true;
                    this.formRules.pulseFrequency[0].required = true;
                    this.formRules.pulsePower[0].required = true;
                    this.formRules.pulseWidth[0].required = true;
                    if (!!this.formInfo.laserPower && !!this.formInfo.pulseFrequency) {
                        var num = this.formInfo.laserPower / this.formInfo.pulseFrequency
                        this.formInfo.pulsePower = Math.round(num * 10) / 10
                        //this.formInfo.pulsePower = num.toFixed(1);
                    };  
                };
            },
            setLaserPower() {
                if (this.formInfo.tempDistribution === 0) {

                } else {
                    if (!!this.formInfo.laserPower && !!this.formInfo.pulseFrequency) {
                        var num = this.formInfo.laserPower / this.formInfo.pulseFrequency
                        this.formInfo.pulsePower = Math.round(num * 10) / 10
                        //this.formInfo.pulsePower = num.toFixed(1);
                    };
                }
               
            },
            setPulseFrequency() {
                if (this.formInfo.tempDistribution === 0) {

                } else {
                    if (!!this.formInfo.laserPower && !!this.formInfo.pulseFrequency) {
                        var num = this.formInfo.laserPower / this.formInfo.pulseFrequency
                        this.formInfo.pulsePower = Math.round(num * 10) / 10
                        //this.formInfo.pulsePower = num.toFixed(1);
                    };
                }
            },
            clearable() {
                this.formInfo.pulsePower = '';
            },
            dialogFormSave() {
                this.$refs.myform.validate().then(suc => {
                    if (!suc) {
                        this.formInfo.laserDID ? this.isAdd = true : this.isAdd = false;
                        this.formLoading = true;
                        !this.formInfo.defocusAmount ? this.formInfo.defocusAmount = null : '';
                        !this.formInfo.washTimes ? this.formInfo.washTimes = null : '';
                        !this.formInfo.laserPower ? this.formInfo.laserPower = null : '';
                        !this.formInfo.pulseFrequency ? this.formInfo.pulseFrequency = null : '';
                        !this.formInfo.pulsePower ? this.formInfo.pulsePower = null : '';
                        !this.formInfo.pulseWidth ? this.formInfo.pulseWidth = null : '';
                        !this.formInfo.scanSpeed ? this.formInfo.scanSpeed = null : '';
                        !this.formInfo.spotDiameter ? this.formInfo.spotDiameter = null : '';
                        !this.formInfo.focalLength ? this.formInfo.focalLength = null : '';
                        prjAPI[this.formInfo.laserDID ? 'updateLaser' : 'createLaser'](this.formInfo).then(res => {
                            if (res) {
                                this.$message({ type: 'success', message: this.isAdd ? '修改成功' : '创建成功' });
                                this.formLoading = false;
                                this.tableShow = false;
                                this.getData(0);
                            } else {
                                this.$message({ type: 'warning', message: this.isAdd ? '修改失败' : '创建失败' });
                                this.formLoading = false;
                                this.tableShow = false;
                                this.getData(0);
                            }

                        }).catch(err => {
                            this.formLoading = false;
                        });
                    }
                }).catch(() => { });
            },
            
            rowClassName({ row }) {
                if (row === this.nowSelectedRow) {
                    return 'colMoveMode';
                }
            },
            handlePageChange({ currentPage, pageSize }) {
                this.tablePage.currentPage = currentPage;
                this.tablePage.pageSize = pageSize;
                this.getData();
            },
            menuClick({ menu, row, rowIndex, column }) {
                if (!row) {
                    return;
                }
                switch (menu.code) {
                    case 'above':
                        this.create(row, true, rowIndex);
                        break;
                    case 'below':
                        this.create(row, false, rowIndex);
                        break;
                    case 'use':
                        this.startUse(row, column);
                        break;
                    case 'useAll':
                        this.startUse(row, column, true);
                        break;
                    case 'setTop':
                        this.setTop(row, rowIndex);
                        break;
                    case 'move':
                        this.startMove(row, rowIndex);
                        break;
                    case 'delete':
                        this.deleteDe(row, true);
                        break;
                };
            },
           
            move(currentID, targetID, isForward) {
                this.loading = true;
                workCardAPI.MoveRI({ currentID, targetID, isForward }).then(res => {
                    this.$message({ type: 'success', message: '移动位置成功!' });
                    this.mode = '';
                    this.nowSelectedRow = null;
                    this.tableModeMessage.close();
                    this.getData();
                }).catch(() => {
                    this.$message({ type: 'info', message: '请再次点击选择需要移动至的行' });
                    this.getData();
                });
            },

            setTop(row, rowIndex) {
                if (this.showDragBtn === true) {
                    this.$message({ type: 'info', message: '当前为拖动排序模式，请关闭后再使用本功能' });
                } else if (rowIndex === -1) {
                    this.$message({ type: 'info', message: '本条数据未保存，不能置顶' });
                } else {
                    this.loading = true;
                    workCardAPI.MoveRI({
                        currentID: row.laserDID,
                        targetID: 0,
                        isForward: true
                    }).then(res => {
                        this.$message({ type: 'success', message: `${row.itemName} 已置顶` });
                        this.getData();
                    }).catch(() => {
                        this.getData();
                    });
                }
            },
            startMove(row, rowIndex) {
                if (this.showDragBtn === true) {
                    this.$message({ type: 'info', message: '当前为拖动排序模式，请关闭后再使用本功能' });
                } else if (rowIndex === -1) {
                    this.$message({ type: 'info', message: '本条数据未保存，不能移动' });
                } else {
                    this.mode = 'move';
                    this.nowSelectedRow = row;
                    if (this.tableModeMessage) {
                        this.tableModeMessage.close();
                    }
                    this.tableModeMessage = this.$message({ type: 'info', message: '请选择需要移动至的行', duration: 0 });
                }
            },
            startUse(row, column, all) {
                var field = column.field;
                if (this.canUseField[field] === true) {
                    if (all) {
                        var text = row[field];
                        var { tableData } = this.$refs.xGrid.getTableData();
                        tableData.map(e => {
                            e[field] = text;
                            return e;
                        });
                        this.getEditNum();
                    } else {
                        this.mode = 'use';
                        this.nowSelectedRow = row;
                        this.nowSelectedField = field;
                        if (this.tableModeMessage) {
                            this.tableModeMessage.close();
                        }
                        this.tableModeMessage = this.$message({ type: 'info', message: '请选择需要覆盖的行（可多选），覆盖后点击保存', duration: 0 });
                    }
                } else {
                    this.$message({ type: 'info', message: '当前单元格数据不能用于覆盖' });
                    this.clearModeStatus();
                }
            },
            clearModeStatus() {
                this.mode = '';
                this.nowSelectedRow = null;
                this.nowSelectedField = null;
                if (this.tableModeMessage) {
                    this.tableModeMessage.close();
                }
            },

            initRowDrop() {
                this.$nextTick(() => {
                    const xGrid = this.$refs.xGrid;
                    this.sortable1 = Sortable.create(xGrid.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
                        handle: '.drag-btn',
                        animation: 150,
                        onEnd: ({ newIndex, oldIndex }) => {
                            const currRow = this.tableData.splice(oldIndex, 1)[0];
                            this.tableData.splice(newIndex, 0, currRow);
                        }
                    });
                });
            },
            showDrag() {
                this.clearModeStatus();
                this.editConfig.enabled = false;
                this.menuConfig.enabled = false;
                this.tablePage.enabled = false;
                this.showDragBtn = true;
                this.$refs.xGrid.showColumn(this.$refs.xGrid.getColumnByField('drag'));
                this.dragDataForm = {
                    originStart: this.tableData[0].sortNum,
                    originEnd: this.tableData[this.tableData.length - 1].sortNum,
                    items: []
                };
                if (this.editItemNum > 0) {
                    this.$confirm(`本页有 ${this.editItemNum} 条数据未保存，是否保存？`, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(() => {
                        this.loading = true;
                        this.save();
                    }).catch(() => {
                        this.loading = true;
                        this.getData();
                    });
                }
            },
            closeDrag() {
                this.showDragBtn = false;
                this.$refs.xGrid.resetColumn(true);
                this.setTableColumn();
                this.getData();
            },
            saveDraggedData() {
                this.loading = true;
                this.dragDataForm.items = this.tableData.map(e => e.laserDID);
                //console.log('拖动后的数据', this.dragDataForm);
                workCardAPI.DragRIs(this.dragDataForm).then(res => {
                    this.$message({ type: 'success', message: '顺序调整成功' });
                    this.closeDrag();
                }).catch(() => {
                    this.closeDrag();
                });
            },

            create(row, isForward, rowIndex) {
                if (this.showDragBtn === true) {
                    this.$message({ type: 'info', message: '当前为拖动排序模式，请关闭后再使用本功能' });
                    return;
                } else if (rowIndex === -1) {
                    this.$message({ type: 'warning', message: '本条数据未保存状态下不能在其前后插入项,请在已保存的数据行内选择插入操作!' });
                    return;
                }
                var item = {
                    prjID: this.taskInfo.prjID,
                    taskID: this.taskInfo.taskID,
                    defocusAmount: '',
                    washTimes: '',
                    laserPower: '',
                    pulseFrequency: '',
                    pulsePower: '',
                    pulseWidth: '',
                    scanSpeed: '',
                    spotDiameter: '',
                    focalLength:'',
                   remark:'',
                };
                var position = null;
                if (!row) {
                    position = -1; // null-第一行 or  -1最后一行
                } else {
                    if (isForward === true) {
                        position = row;
                    } else {
                        var i = this.tableData.findIndex(e => e.laserDID === row.laserDID);
                        if (i === this.tableData.length - 1) {
                            position = -1;
                        } else {
                            position = this.tableData[i + 1];
                        }
                    }
                }
                this.$refs.xGrid.insertAt(item, position);
            },
            deleteDe(row, noRefresh) {
                var repoPItem = this.selectedItems.filter(e => e.laserDID == undefined);
                var tabNumb = this.$refs.xGrid.getTableData().tableData.length;
                if (row) {
                    if (this.tableData.length < tabNumb && row.laserDID) {
                        this.$message({ type: 'warning', message: '本页有数据未保存，请先保存后再进行删除操作!' });
                        return;
                    };
                } else {
                    if (this.tableData.length < tabNumb && repoPItem.length !== this.selectedItems.length) {
                        this.$message({ type: 'warning', message: '本页有数据未保存，请先保存后再进行删除操作!' });
                        return;
                    };
                };
                var title = row ? `是否删除故障项 ${row.itemName}` : `是否删除已选中的 ${this.selectedItems.length} 条故障项`;
                this.$confirm(title, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if (row && !row.laserDID) {
                        this.$refs.xGrid.remove(row);
                        this.getEditNum();
                        return;
                    };
                    if (!noRefresh) {
                        this.loading = true;
                        if (this.tableData.length < tabNumb && repoPItem.length === this.selectedItems.length) {
                            this.$refs.xGrid.remove(this.selectedItems);
                            this.selectedItems = [];
                            this.getEditNum();
                            this.loading = false;
                            this.$message({ type: 'success', message: '删除成功!' });
                            return;
                        }
                    }
                    var itemID = row ? [row.laserDID] : this.selectedItems.map(e => e.laserDID);
                    workCardAPI.deleteRIs(itemID).then(res => {
                        this.$message({
                            type: !res ? 'warning' : 'success',
                            message: !res ? '删除失败!' : '删除成功!'
                        });
                        if (!noRefresh) {
                            this.getData();
                        } else {
                            if (!!res && row) {
                                this.$refs.xGrid.remove(row);
                                this.getData();
                            }
                        }
                        if (!!res) {
                            this.selectedItems = this.selectedItems.filter(e => itemID.includes(e.laserDID) === false);
                        }
                        this.getEditNum();
                    }).catch(err => {
                        if (!noRefresh) {
                            //this.getData();
                        }
                        this.getEditNum();
                    });
                }).catch(() => { });
            },
            save() {
                this.$refs.xGrid.validate().then(suc => {
                    if (!suc) {
                        var { insertRecords, updateRecords, removeRecords } = this.$refs.xGrid.getRecordset();
                        if (insertRecords.length > 0 || updateRecords.length > 0 || removeRecords.length > 0) {
                            this.loading = true;
                            //var remove = removeRecords.map(e => {
                            //    return e.laserDID
                            //});
                            var insert = [];
                            insertRecords.forEach(item => {
                                var i = insert.findIndex(e => e.targetID === item.targetID && e.isForward === item.isForward);
                                if (i === -1) {
                                    insert.push({
                                        targetID: item.targetID,
                                        isForward: item.isForward,
                                        items: [item]
                                    });
                                } else {
                                    if (insert[i].targetID === 0) {
                                        insert[i].items.unshift(item);
                                    } else {
                                        insert[i].items.push(item);
                                    }
                                }
                            });
                            if (this.tablePage.total !== 0) {
                                insert.map(item => {
                                    item.items = item.items.reverse();
                                    return item;
                                });
                            }
                            //console.log(insert);
                            //return;
                            var apis = [
                                //workCardAPI.createRIs(insertRecords),
                                workCardAPI.InsertRIs(insert),
                                workCardAPI.updateRIs(updateRecords),
                                //workCardAPI.deleteRIs(remove),
                            ];
                            Promise.all(apis).then(res => {
                                if (this.tableModeMessage) {
                                    this.tableModeMessage.close();
                                }
                                this.$nextTick(() => {
                                    this.$message({ type: 'success', message: '保存成功' });
                                    this.goBack();
                                });
                            }).catch(err => {
                                this.loading = false;
                            });
                        } else {
                            this.$message({ type: 'info', message: '无修改项' });
                        };
                    }
                }).catch(err => { });
            },
            editActived({ row, column, rowIndex }) {
                //this.editActive = {
                //    PGCS: column.field === 'measure',
                //    KYYJ: column.field === 'investigaion'
                //};
            },
            editClosed({ row, rowIndex }) {
                this.editActive = {
                    PGCS: false,
                    KYYJ: false
                };
                this.getEditNum();
            },
            getEditNum() {
                if (this.$refs.xGrid) {
                    var { insertRecords, updateRecords } = this.$refs.xGrid.getRecordset();
                    this.editItemNum = insertRecords.length + updateRecords.length;
                }
            },
            getAddEditNum() {
                this.getEditNum();
                this.$emit('getEditNum', this.editItemNum)
            },

            getAllRepairMeasure() {
                repMeasureAPI.getAllByProf({
                    profID: this.workCardInfo.profID
                }).then(res => {
                    this.repairMeasure = res.map(item => {
                        return {
                            value: item.measure
                        };
                    });
                }).catch(err => { });
            },
            querySearch(queryString, cb) {
                cb(this.repairMeasure);
            },
            focusEvent(type) {
                this.editActive[type] = true;
                if (type === 'PGCS') {
                    this.$refs.vxepulldown.showPanel();
                }
            },
            focusEvent2(type) {
                this.editActive[type] = false;
                if (type === 'PGCS') {
                    this.$refs.vxepulldown.hidePanel();
                }
            },
            selectMeasure(row, item) {
                var txt = document.getElementsByName('textareaG')[0];
                if (txt.selectionStart || txt.selectionStart === 0) {
                    var startPos = txt.selectionStart;
                    var endPos = txt.selectionEnd;
                    row.measure = txt.value.substring(0, startPos) + item.value + txt.value.substring(endPos, txt.value.length);
                    this.$nextTick();
                    txt.focus()
                    txt.setSelectionRange(endPos + item.value.length, endPos + item.value.length);
                } else {
                    row.measure += item.value;
                }
                this.$refs.vxepulldown.hidePanel();
            },
            closeEdit(type) {
                //遮罩层
                //this.editActive[type] = false;
                //this.$refs.xGrid.clearEdit();
            },

            goBack() {
                this.loading = false;
                this.selectedItems = [];
                this.getData();
            },

            checkboxChange({ checked, row }) {
                this.selectedItems = this.$refs.xGrid.getCheckboxRecords();
                //var has = this.selectedItems.findIndex(e => e.laserDID === row.laserDID);
                //if (checked && has === -1) {
                //    this.selectedItems.push(row);
                //} else if (!checked && has > -1) {
                //    this.selectedItems.splice(has, 1);
                //};
            },
            checkboxAll({ checked }) {
                this.selectedItems = this.$refs.xGrid.getCheckboxRecords(true);
                //var arr = this.$refs.xGrid.getCheckboxRecords(true);
                //if (checked === true) {
                //    arr.forEach((item, i) => {
                //        var has = this.selectedItems.findIndex(e => e.laserDID === item.laserDID);
                //        if (has === -1) {
                //            this.selectedItems.push(item);
                //        };
                //    });
                //} else {
                //    this.tableData.forEach((item, i) => {
                //        var has = this.selectedItems.findIndex(e => e.laserDID === item.laserDID);
                //        if (has > -1) {
                //            this.selectedItems.splice(has, 1);
                //        };
                //    })
                //}
            },
            clearContext(row) {
                row.measure = '';
            },
            closeContext() {
                this.editActive.PGCS = false;
            },
            clearContext2(row) {
                row.investigaion = '';
            },
            closeContext2() {
                this.editActive.KYYJ = false;
            },
            fx() {
                var tableData = this.$refs.xGrid.getTableData().tableData;
                this.selectedItems = [];
                for (var i = 0; i < tableData.length; i++) {
                    if (this.$refs.xGrid.isCheckedByCheckboxRow(tableData[i])) {
                        this.$refs.xGrid.setCheckboxRow(tableData[i], false);
                    } else {
                        this.$refs.xGrid.setCheckboxRow(tableData[i], true);
                        this.selectedItems.push(tableData[i]);
                    }
                };
                //var t = [];
                //var f = [];
                //this.tableData.filter(item => {
                //    var has = this.selectedItems.findIndex(e => e.laserDID === item.laserDID);
                //    if (has === -1) {
                //        t.push(item);
                //        this.selectedItems.push(item);
                //    } else {
                //        f.push(item);
                //        this.selectedItems.splice(has, 1);
                //    }
                //});
                //this.$refs.xGrid.setCheckboxRow(t, true);
                //this.$refs.xGrid.setCheckboxRow(f, false);
            },
            checkboxChange2({ checked, row }) {
                this.selectedProjs = this.$refs.xGrid2.getCheckboxRecords();
            },
            checkboxAll2({ checked }) {
                this.selectedProjs = this.$refs.xGrid2.getCheckboxRecords(true);
            },
            deleteDeFault() {
                if (this.editItemNum > 0) {
                    this.$message({ type: 'warning', message: '本页有数据未保存，请先保存后再进行删除操作!' });
                    return;
                };
                var title = `已选中${this.selectedProjs.length} 条故障项,删除后对应工卡内数据也将被删除,是否继续?`;
                this.$confirm(title, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var itemID = this.selectedProjs.map(e => e.laserDID);
                    workCardAPI.deleteRIs(itemID).then(res => {
                        this.$message({
                            type: !res ? 'warning' : 'success',
                            message: !res ? '删除失败!' : '删除成功!'
                        });
                        this.selectedProjs = [];
                        this.getOtherFault(0);
                        this.getEditNum();
                        this.getData();
                    }).catch(err => {
                        this.getEditNum();
                    });
                }).catch(() => { });
            },
            profClass(row) {
                return {
                    profRowActive: row.profID === this.nowSelectProfID,
                    profRow: true
                };
            },
            async beforeRelay(row) {
                this.nowSelectItem = row;
                this.showRelay = true;
                this.loadingWC = true;
                this.workCards = [];
                //await this.getProf();
                await this.getWorkCard();
            },
            getProf() {
                return new Promise((resolve, reject) => {
                    this.prof = [];
                    this.loadingProf = true;
                    profAPI.getAllProfs().then(res => {
                        this.prof = res;
                        this.loadingProf = false;
                        if (this.workCardInfo.profID === this.nowSelectProfID) {
                            this.getWorkCard();
                        }
                        resolve();
                    }).catch(err => {
                        this.loadingProf = false;
                        resolve();
                    });
                });
            },
            selectProfID(row) {
                this.nowSelectProfID = row.profID;
                this.getWorkCard();
            },
            relayToProf(row) {
                var itemID = this.selectedItems.map(e => e.laserDID);
                this.loadingRelay = true;
                workCardAPI.relayToProf({ rItemIDs: itemID, profID: row.profID }).then(res => {
                    this.$message({ type: 'success', message: '故障项已转发至' + row.profName + '专业' });
                    this.showRelay = false;
                    this.loadingRelay = false;
                    this.selectedItems = [];
                    this.getData();
                }).catch(err => {
                    this.loadingRelay = false;
                });
            },

            getWorkCard() {
                return new Promise((resolve, reject) => {
                    this.workCards = [];
                    this.loadingWC = true;
                    if (this.workCardInfo.profID === this.nowSelectProfID) {
                        workCardAPI.getAllByQuery({
                            pageIndex: 0,
                            pageSize: 50,
                            projectID: this.workCardInfo.projectID,
                            profID: this.nowSelectProfID
                        }).then(res => {
                            this.workCards = res.result;
                            this.loadingWC = false;
                        }).catch(err => {
                            this.loadingWC = false;
                        });
                    } else {
                        this.loadingWC = false;
                    }
                });
            },
            relayToWorkCard(row) {
                var itemID = this.selectedItems.map(e => e.laserDID);
                this.loadingRelay = true;
                workCardAPI.relayToWC({ rItemIDs: itemID, wcid: row.wcid }).then(res => {
                    this.$message({ type: 'success', message: '故障项已转发至' + row.wcName + '工卡' });
                    this.showRelay = false;
                    this.loadingRelay = false;
                    this.selectedItems = [];
                    this.getData();
                }).catch(err => {
                    this.loadingRelay = false;
                });
            },

            setTableColumn() {
                this.$refs.xGrid.resetColumn(true);
                this.editConfig.enabled = this.canEdit;
                this.menuConfig.enabled = this.canEdit;
                this.tablePage.enabled = true;
                if (this.canEdit === true) {
                    //this.$refs.xGrid.showColumn(this.$refs.xGrid.getColumnByField('operate'));
                    this.$refs.xGrid.showColumn(this.$refs.xGrid.getColumnByField('checkbox'));
                } else {
                    this.$refs.xGrid.resetColumn(true);
                };
            },

            disabledZFGK(row) {
                var obj = this.projectGRJSON.workCardStatus.find(e => e.value === row.status);
                return obj.canEdit;
            },
            tooltipZFGK(row) {
                var obj = this.projectGRJSON.workCardStatus.find(e => e.value === row.status);
                var tooltip = obj.canEdit === false ? `该工卡状态为“${obj.label}”,故无法转发` : '';
                return tooltip;
            },
            classZFGK(row) {
                return {
                    profRelay: true,
                    profRelayDisabled: row.status === 3 || row.status === 4 || row.wcid === this.workCardInfo.wcid
                };
            },
            showOtherFaultModal() {
                this.otherFaultShow = true;
                this.faultFilter = null;
                this.getOtherFault(0);
            },
            getOtherFault(type) {
                this.faultList = [];
                this.wcidArr = [];
                this.faultLoading = true;
                if (type === 0) {
                    this.faultTablePage.currentPage = 1;
                };
                var parmas = {
                    pageIndex: this.faultTablePage.currentPage - 1,
                    pageSize: this.faultTablePage.pageSize,
                    itemName: this.faultFilter,
                    wcid: this.workCardInfo.wcid,
                    prjID: this.workCardInfo.projectID,
                    profID: this.profType ? this.profType : 0,
                    isImportant: this.isFaultImportant,
                };
                workCardAPI.getRepairItemPager(parmas).then(res => {
                    //var data;
                    //if (this.isFaultImportant === null) {
                    //    data = res;
                    //} else if (this.isFaultImportant === null) {
                    //    data = res.result.
                    //}
                    this.faultList = res.result.result;
                    this.wcidArr = res.wordCardNameDic;
                    this.faultTablePage.total = res.result.recordCount;
                    this.faultLoading = false
                }).catch(() => {
                    this.faultLoading = false;
                });
            },
            createPrjProblems() {
                var data = this.selectedItems.map(e => e.laserDID);
                var loadingFullScreen = this.$loading({
                    lock: true,
                    text: '正在转发',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.3)'
                });
                workCardAPI.createPrjProblems(data).then(res => {
                    this.selectedItems = [];
                    this.$refs.xGrid.clearCheckboxRow();
                    loadingFullScreen.close();
                    this.$message({ type: 'success', message: '转发完成!' });
                }).catch(() => {
                    loadingFullScreen.close();
                });
            },
            faultTableHandlePage({ currentPage, pageSize }) {
                this.faultTablePage.currentPage = currentPage;
                this.faultTablePage.pageSize = pageSize;
                this.getOtherFault();
            },
            exportMethod() {
                var body = {
                    queryPara: this.faultFilter,
                    prjid: this.workCardInfo.projectID
                };
                var loadingFullScreen = this.$loading({
                    lock: true,
                    text: '正在导出',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.3)'
                });
                workCardAPI.getExportRepairItem(body).then(res => {
                    const blob = new Blob([res], { type: 'text/plain;charset=utf-8' });
                    if ('download' in document.createElement('a')) {
                        // 非IE下载
                        const elink = document.createElement('a');
                        elink.download = this.projectInfo.projectName + '故障项清单.xlsx';
                        elink.style.display = 'none';
                        elink.href = URL.createObjectURL(blob);
                        document.body.appendChild(elink);
                        elink.click();
                        URL.revokeObjectURL(elink.href);
                        document.body.removeChild(elink);
                    } else {
                        // IE10+下载
                        navigator.msSaveBlob(blob, this.projectInfo.projectName + '故障项清单.xlsx');
                    }
                    loadingFullScreen.close();
                }).catch(() => {
                    loadingFullScreen.close();
                    this.$message({ type: 'error', message: '导出失败' });
                });
            },
            format(ops, op, hasops) {
                var val = null;
                if (hasops) {
                    var options = ops.map(e => {
                        return e.options;
                    }).flat().valueOf();
                    val = options.find(e => e.value === op);
                } else {
                    val = ops.find(e => e.value === op);
                }
                return val ? val.label : '';
            },
            toDate(date) {
                return date ? moment(date).format("YYYY-MM-DD") : "";
            },
            getUser(date) {
                return date ? JSON.parse(sessionStorage.getItem('userList')).find(x => x.userid === date).realname : '';
            },
            watchKeyDown() {
                var _this = this;
                window.onkeyup = (e) => {
                    e.preventDefault(); // 阻止原有按键功能事件
                    var el = e || window.event || arguments.callee.caller.arguments[0];
                    if (el.keyCode === 27) {
                        _this.editActive.PGCS = false;
                        _this.editActive.KYYJ = false;
                    }
                };
            }
        },
        template: `#template`
    };
</script>
